package com.wudizaba.mqtt.demos.web.service.serviceImpl;

import com.wudizaba.mqtt.demos.web.service.providerService;

import com.wudizaba.nb.domain.mqttContext;
import lombok.SneakyThrows;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.stereotype.Service;

@Service
public class providerServiceImpl implements providerService {

    @SneakyThrows
    @Override
    public void testClientToMqtt() {
        System.out.println("=======模拟IOT系统订阅mqtt主题======");

        MqttClient client = new MqttClient(mqttContext.BROKER, mqttContext.PUBLISH_CLIENT_ID, new MemoryPersistence());
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName(mqttContext.USERNAME);
        options.setPassword(mqttContext.PASSWORD.toCharArray());

        //连接服务器
        client.connect(options);
        System.out.println("连接服务器成功");
        System.out.println("=============================================");

        //创建消息，设置QoS
        //模拟plc数据
        String Message = "{\n" +
                "    \"name\": \"BeJson\",\n" +
                "    \"url\": \"http://www.bejson.com\",\n" +
                "    \"page\": 88,\n" +
                "    \"isNonProfit\": true,\n" +
                "    \"address\": {\n" +
                "        \"street\": \"科技园路.\",\n" +
                "        \"city\": \"江苏苏州\",\n" +
                "        \"country\": \"中国\"\n" +
                "    },\n" +
                "    \"links\": [\n" +
                "        {\n" +
                "            \"name\": \"Google\",\n" +
                "            \"url\": \"http://www.google.com\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"name\": \"Baidu\",\n" +
                "            \"url\": \"http://www.baidu.com\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"name\": \"SoSo\",\n" +
                "            \"url\": \"http://www.SoSo.com\"\n" +
                "        }\n" +
                "    ]\n" +
                "}";
        MqttMessage mqttMessage = new MqttMessage(Message.getBytes());
        mqttMessage.setQos(mqttContext.QoS_2);//设置QoS，只发送一次
        //发布消息
        client.publish(mqttContext.TOPIC, mqttMessage);
        System.out.println(mqttMessage.toString());
        System.out.println("=============================================");
        System.out.println("发布消息成功");
        //断开连接
        client.disconnect();
        System.out.println("断开连接成功");
        System.out.println("=============================================");

        //关闭连接
        client.close();
        System.out.println("关闭连接成功");
        System.out.println("=============================================");
    }
}
